/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.service;

import br.com.foxline.enums.StatusSale;
import br.com.foxline.model.*;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.Query;

/**
 *
 * @author luciano
 */
@Stateless
public class PendingService extends GenericService<Pending> {

    @EJB
    UserService usersService;
    @EJB
    MessageService messageService;
    @EJB
    SaleService saleService;
    @EJB
    EnterpriseService enterpriseService;
    @EJB
    CorrectorService correctorService;

    public PendingService() {
        super(Pending.class);
    }

    public void save(Pending pending) {
        Users to;
        Users from;
        Sale s = pending.getSale();
        boolean wasRead = false;
        from = usersService.userByLoginName(usersService.getCurrentUser());
        String message = pending.getDescription();
        String subject = "Status da venda alterado";

        if (pending.getStatusSale().equals(StatusSale.WAITING_APPROVAL)) {
            Sale s2 = saleService.find(pending.getSale().getId());
            subject = "Venda esperando aprovação";
            Enterprise e = enterpriseService.find(s2.getEnterprise().getId());
            to = usersService.find(e.getAdmin().getId());
        } else {
            Sale s2 = saleService.find(pending.getSale().getId());
            Corrector c = correctorService.find(s2.getCorrector().getId());
            to = usersService.find(c.getUser().getId());
        }

        Message m = new Message(from, to , subject, message, s, wasRead);

        messageService.save(m);
        super.save(pending);
    }

    public List<Pending> pendingBySale(Sale s) {
        List<Pending> lista = new ArrayList<Pending>();
        //   try {
        String sql = "Select p from Pending p JOIN p.sale s where s.id=:id ORDER BY p.dataPendencia";
        Query query = getEntityManager().createQuery(sql).setMaxResults(50);
        query.setParameter("id", s.getId());
        lista = query.getResultList();

        //  } catch (Exception e) {
        //       e.printStackTrace();
        //   }
        return lista;
    }
}
